<template>
  <div class="tree">
    tree
  </div>
</template>

<script lang="ts">
import { Component, Vue } from 'vue-property-decorator';

@Component({
  components: {}
})
export default class Tree extends Vue {
  data = [
    { id: 1, name: '办公管理', pid: 0 },
    { id: 2, name: '请假申请', pid: 1 },
    { id: 3, name: '出差申请', pid: 1 },
    { id: 4, name: '请假记录', pid: 2 },
    { id: 5, name: '系统设置', pid: 0 },
    { id: 6, name: '权限管理', pid: 5 },
    { id: 7, name: '用户角色', pid: 6 },
    { id: 8, name: '菜单设置', pid: 6 },
    { id: 9, name: '打开开关', pid: 5 },
    { id: 10, name: '超级管理员', pid: 7 }
  ];
  // 封装函数
  setTreeDate(source: any) {
    const cloneData = JSON.parse(JSON.stringify(source)); // 对源数据深度克隆
    return cloneData.filter((father: any) => {
      const brachArr = cloneData.filter((child: any) => father.id === child.pid); // 返回每一项的子级数组
      brachArr.length > 0 ? (father.children = brachArr) : ''; // 如果存在子级，则给父级添加一个children属性，并赋值
      return father.pid == 0; // 返回第一层
    });
  }
  created() {
    console.log(this.setTreeDate(this.data));
  }
}
</script>
<style lang="less" scoped></style>
